<template>
    <div>
        <Card>
            <Row>
                <Col span="24"><h3>流程图</h3></Col>
            </Row>
            <Row>
                <Col span="24">
                    <div v-viewer="{movable: true}">
                        <img :src="processImage" width="100%">
                    </div>
                </Col>
            </Row>
            <Row>
                <Col span="24"><h3>审批进度历史</h3></Col>
            </Row>
            <Row>
                <Col span="24">
                    <Table size="small" :columns="columns" :data="tableData"></Table>
                    <Pagination
                            ref="pagination"
                            size="small"
                            :sizer="true"
                            :page.sync="listQuery.pageNumber"
                            :rows.sync="listQuery.pageSize"
                            :total="total"
                            @on-change="getTableData"/>
                </Col>
            </Row>
            <Row>
                <Col span="24">
                    <Form :model="formData" :label-width="100" style="margin: 20px 0">
                        <FormItem label="原因：">
                            <Input type="textarea" v-model="formData.message" placeholder="请输入原因..."></Input>
                        </FormItem>
                        <FormItem label="流程变量：">
                            <Input type="textarea" v-model="formData.variables" placeholder="{'key':'value'}"></Input>
                        </FormItem>
                        <FormItem label="操作：">
                            <Button class="my-btn" type="primary" @click="executeTask('claim')">签收</Button>
                            <Button class="my-btn" type="primary" @click="executeTask('unclaim')" disabled>反签收</Button>
                            <Tooltip content="审批前，请签收任务">
                                <Button class="my-btn" type="primary" @click="executeTask('complete')">通过<!--完成--></Button>
                            </Tooltip>
                            <Button class="my-btn" type="primary" @click="executeTask('delegate')" disabled>任务委派</Button>
                            <Button class="my-btn" type="primary" @click="executeTask('resolve')" disabled>退回发起人</Button>
                            <Button class="my-btn" type="primary" @click="executeTask('assignee')" disabled>转办</Button>
                            <Button class="my-btn" type="primary" @click="executeTask('rollback')" disabled>回退</Button>
                        </FormItem>
                    </Form>
                </Col>
            </Row>
        </Card>
    </div>
</template>

<script>
    import {findRecordsPage, executeTask, addComment} from '@/api/workflow';
    import Pagination from '../components/Pagination' // 分页插件
    import ExpandRow from './records/table-expand.vue';
    import axios from 'axios'
    import {getAccessToken} from '@/utils/auth'


    export default {
        name: "Execute",
        data() {
            return {
                columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        type: 'expand',
                        width: 50,
                        render: (h, params) => {
                            return h(ExpandRow, {
                                props: {
                                    row: params.row
                                }
                            })
                        }
                    },
                    {
                        title: '任务名称',
                        key: 'activityName'
                    },
                    {
                        title: '任务类型',
                        key: 'activityType'
                    },
                    {
                        title: '操作人',
                        key: 'assigneeName'
                    },
                    {
                        title: '开始时间',
                        key: 'startTime',
                        width: 150,
                    },
                    {
                        title: '结束时间',
                        key: 'endTime',
                        width: 150,
                    },
                    {
                        title: '耗时(ms)',
                        key: 'durationInMillis'
                    },
                    {
                        title: '回退信息',
                        key: 'rollback',
                        width: 150,
                        render: (h, params) => {
                            if (!!params.row.rollback) {
                                return h('span',
                                    [h('Icon', {attrs: {type: "ios-information-circle"}, style: {color: "red"}}),
                                        h('span', params.row.rollback)]
                                )
                            } else {
                                return h('span', "--")
                            }
                        }
                    }
                ],
                tableData: [],
                listQuery: {
                    pageNumber: 1,
                    pageSize: 10,
                },
                total: 0,
                processImage: '',
                formData: {},
            }
        },
        components: {
            Pagination, ExpandRow
        },
        created() {
            this.getTableData();
        },
        methods: {
            async getTableData() {
                let processInstanceId = this.$route.query.processInstanceId;
                let executionId = this.$route.query.executionId;
                let taskId = this.$route.query.taskId;
                this.formData.processInstanceId = processInstanceId;
                this.formData.taskId = taskId;
                //打开弹窗钱，清除数据
                this.processImage = "";
                this.tableData = [];
                this.total = 0;
                //历史记录
                let params = this.listQuery;
                params.processInstanceId = processInstanceId
                if (!!this.executionId) {
                    params.executionId = this.executionId;
                }
                let res = await findRecordsPage(params);
                if (res.success) {
                    this.tableData = res.result.records;
                    this.total = res.result.total;
                }
                console.log("process.env.VUE_APP_BASE_API=", process.env.VUE_APP_BASE_API);
                //查看流程图
                let url = process.env.VUE_APP_BASE_API + `/workflow/resource/flowDiagram?processInstanceId=` + processInstanceId;
                if (!!executionId) {
                    url += `&executionId=` + executionId;
                }
                await axios({
                    method: 'GET',
                    url: url,
                    responseType: 'arraybuffer',
                    headers: {
                        'accessToken': getAccessToken()
                    }
                }).then(res => {
                    this.processImage = 'data:image/png;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
                }).catch(resp => {
                    // this.$message.error(response);
                    console.log("resp=", resp);
                });
            },
            // 办理
            async executeTask(action) {
                this.addComment()
                let user = JSON.parse(localStorage.getItem("user"));
                let params = {
                    taskId: this.formData.taskId,
                    action: action,
                    localScope: false,
                    assignee: user.id,
                    variables: {success: 'success'}
                }
                let res = await executeTask(params);
                if (res.success) {
                    this.$layer.msg(res.message, {icon: 1, time: 3});

                    this.$router.push({ path: "/backlog"})
                    // this.getTableData()
                }
            },
            //添加评论
            async addComment() {
                let user = JSON.parse(localStorage.getItem("user"));
                let params = {
                    taskId: this.formData.taskId,
                    processInstanceId: this.formData.processInstanceId,
                    message: this.formData.message,
                    userId: user.id,
                }
                let res = await addComment(params);
                if (res.success) {
                    // this.$layer.msg(res.message, {icon: 1, time: 3});
                    console.log(res.message);
                }
            }
        }
    }
</script>

<style scoped>
</style>
